#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:        forms
# Author:      KuKei
# Create Date: 2011-04-18
# Description: 表单目录
# Modify Date: 2011-04-18

from django.core.exceptions import ValidationError
from django import forms

class MyForm:
    #需要本地验证的字段
    id = -1
    cValid = []
    initDic = {}
    myErrors = {}
    def GetErrors(self):
        retStr = ''
        self.myErrors = {}
        if self.errors:
            for k,v in self.errors.iteritems():
                self.myErrors[k] = self.fields[k].label+u'：'+v[0]
        for v in self.myErrors.values():
            retStr += '<br />'+v
        return retStr
    
    def clearErrors(self):
        errorlist = []
        if self.errors:
            for k,v in self.errors.iteritems():
                errorlist.append(k)
            for k in errorlist:
                del self.errors[k]
        
    #此函数是想自定义错误提示信息，但是还不能使用
    def fieldClean(self, name, value):
        try:
            self.fields[name].clean(value);
        except ValidationError, e:
            self.errors[name] = self.error_class(e.messages)
        return self.errors[name] if self.errors.has_key(name) else None
    
    def modelToDic(self, modelData):
        self.initDic = {}
        if modelData:
            for field in iter(self._meta.fields):
                modelValue = getattr(modelData, field, None);
                if modelValue:
                    if isinstance(modelValue, (int, long, str, unicode)):
                        self.initDic[field] = modelValue;
                    else:
                        try:
                            #如果是模型实例就去id
                            self.initDic[field] = getattr(modelValue, 'id', None);
                        except Exception:
                            pass
        if self.initDic:
            self.id = getattr(modelData, 'id', None) or -1
        return self.initDic
    
    def initOptions(self, name, listValue):
        try:
            self.fields[name].widget.choices = listValue
            self.fields[name].choices = listValue
        except Exception, ex:
            pass

    
#表单基类
class BaseForm(forms.Form, MyForm):        
    def __init__(self, baseview=None, initial=None):
        self.bv = baseview
        if self.bv:
            forms.Form.__init__(self, data=self.bv.request.POST, files=None, auto_id='id_%s', prefix=None,
                 initial=initial, label_suffix=':',empty_permitted=False)
        else:
            forms.Form.__init__(self)

    class Meta:
        #Meta中的abstract属性表明此类为抽象类，可以做基类；
        abstract = True
        
class BaseModelForm(forms.ModelForm, MyForm):
    def __init__(self, baseview=None, modelData = None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, label_suffix=':',empty_permitted=False):
        self.bv = baseview
        if self.bv:
            self.id = int(self.bv.request.POST['_id']) if self.bv.request.POST.has_key('_id') and len(self.bv.request.POST['_id'])>0 else -1;
        self.modelToDic(modelData)
        data = self.initDic or self.bv.request.POST if self.bv else None
        forms.ModelForm.__init__(self, data=data, files=files, auto_id=auto_id, prefix=prefix,
             initial=initial, label_suffix=label_suffix ,empty_permitted=empty_permitted)
    
    class Meta:
        #Meta中的abstract属性表明此类为抽象类，可以做基类；
        abstract = True
    
    def to_table(self):
        return self._html_output(
            normal_row = u'<tr%(html_class_attr)s><th>%(label)s</th><td class="fieldclass">%(field)s</td><td  class="infoclass">%(errors)s%(help_text)s</td></tr>',
            error_row = u'<tr><td colspan="2">%s</td></tr>',
            row_ender = u'</td></tr>',
            help_text_html = u'<span class="helptext">%s</span>',
            errors_on_separate_row = False)
    